<template>
  <div>
    <a-table
      :pagination="false"
      :columns="columns"
      :data-source="data"
      :scroll="{ x: 1500 }"
      :row-key="(record) => record.code"
      :rowExpandable="(record) => record.isShowIcon"
      @expand="rowData"
      v-model:expandedRowKeys="defaultExpandedRowKeys"
      class="components-table-demo-nested"
    >
      <template #bodyCell="{ column, record, index }">
        <!-- 文件名称 -->
        <template v-if="column.dataIndex == 'name'">
          <div>
            <a-select
              :dropdownStyle="{ minHeight: '350px', minWidth: '350px' }"
              :style="[{ width: '100%' }, record.nameRequired ? { border: '1px solid red' } : {}]"
              v-model:value="record.name"
              @blur="inputValueName(record)"
              @dropdownVisibleChange="launchName(index)"
              placeholder="请输入"
            >
              <template #notFoundContent>
                <!-- <a-input placeholder="请输入搜索" v-model:value="searchValue">
                  <template #suffix>
                    <div style="color: rgb(172, 173, 175)" @click="onSearch">
                      <search-outlined />
                    </div>
                  </template>
                </a-input> -->
                <a-table :pagination="false" :scroll="{ y: 400 }" :dataSource="fileNameData" :columns="fileNameColumn" :customRow="rowClick" />
              </template>
              <!-- <template #suffixIcon>
                <div style="color: rgb(172, 173, 175)" @click="onSearch(record.name)">
                  <search-outlined /></div
              ></template> -->
            </a-select>
            <span v-if="record.nameRequired" class="holder">请输入</span>
          </div>
        </template>

        <!-- 文件类型 -->
        <template v-if="column.dataIndex == 'directoryId'">
          <div>
            <a-tree-select
              v-model:value="record.directoryId"
              v-model:searchValue="searchValueType"
              show-search
              :style="[{ width: '100%' }, record.typeRequired ? { border: '1px solid red' } : {}]"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto', minWidth: '250px' }"
              placeholder="请选择"
              allow-clear
              :field-names="{ label: 'name', value: 'id', children: 'children' }"
              tree-default-expand-all
              :tree-data="treeDataType"
              tree-node-filter-prop="name"
              @blur="inputValueType(record)"
            >
              <template #suffixIcon>
                <SearchOutlined style="color: #999" />
              </template>
            </a-tree-select>
            <span v-if="record.typeRequired" class="holder">请选择</span>
          </div>
        </template>

        <!-- 保密等级 -->
        <!-- <template v-if="column.dataIndex == 'securityLevel'">
          <div>
            <a-select
              :style="[{ width: '110px' }, record.securityLevelRequired ? { border: '1px solid red' } : {}]"
              v-model:value="record.securityLevel"
              :options="LevelOptions"
              :allowClear="false"
              placeholder="请选择"
              @blur="inputValueSecurityLevel(record)"
            />
            <span v-if="record.securityLevelRequired" class="holder">请选择</span>
          </div>
        </template> -->

        <!-- 是否文件模板 -->
        <template v-if="column.dataIndex == 'isTemplate'">
          <div>
            <a-select
              :style="[{ width: '110px' }, record.isTemplateRequired ? { border: '1px solid red' } : {}]"
              v-model:value="record.isTemplate"
              :options="templateOptions"
              :allowClear="false"
              placeholder="请选择"
              @blur="inputValueIsTemplate(record)"
            />
            <span v-if="record.isTemplateRequired" class="holder">请选择</span>
          </div>
        </template>

        <!-- 文件负责人 -->
        <template v-if="column.dataIndex == 'principalId'">
          <div>
            <a-select
              :style="[{ width: '100%' }, record.personRequired ? { border: '1px solid red' } : {}]"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto', maxWidth: '250px' }"
              v-model:value="record.principalId"
              :options="subjectOptions"
              show-search
              :filter-option="filterOptionSubject"
              :allowClear="false"
              :field-names="{
                label: 'nickName',
                value: 'id'
              }"
              :dropdownMatchSelectWidth="true"
              placeholder="请选择"
              @blur="inputValuePerson(record)"
            />
            <span v-if="record.personRequired" class="holder">请选择</span>
          </div>
        </template>
        <!-- 关键字 -->
        <template v-if="column.dataIndex == 'keyword'">
          <div>
            <a-input v-model:value="record.keyword" />
          </div>
        </template>
        <!-- 主要内容 -->
        <template v-if="column.dataIndex == 'mainContent'">
          <div>
            <a-input v-model:value="record.mainContent" />
          </div>
        </template>
        <!-- 申请原因 -->
        <template v-if="column.dataIndex == 'applyReason'">
          <div>
            <a-input v-model:value="record.applyReason" />
          </div>
        </template>
        <!-- 删除项 -->
        <template v-else-if="column.key === 'operation'">
          <a-dropdown v-if="record.name" placement="bottom">
            <span class="form-table-actions">上传 <DownOutlined /></span>
            <template #overlay>
              <a-menu>
                <a-menu-item @click.prevent="onUpload(record, index)">
                  <span>上传</span>
                </a-menu-item>
                <a-menu-item @click.prevent="associatedUpload(record, index)">
                  <span>个人文件关联上传</span>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
          <span @click.prevent="onDelete(record.code)" class="form-table-actions">删除</span>
        </template>
      </template>
      <!-- 必填选项 -->
      <template #headerCell="{ column }"
        ><template v-if="column.key === 'name'"><span class="form-table-heard">文件名称</span></template>
        <template v-else-if="column.key === 'code'"><span class="form-table-heard">文件编码</span></template>
        <template v-else-if="column.key === 'directoryId'"><span class="form-table-heard">文件类型</span></template>
        <template v-else-if="column.key === 'version'"><span class="form-table-heard">版本号</span></template>
        <!-- <template v-else-if="column.key === 'securityLevel'"
          ><span class="form-table-heard">保密等级 </span>
          <a-tooltip placement="top" :overlayStyle="{ maxWidth: '655px' }">
            <template #title>
              <p>
                <span>1、绝密：指一旦泄密会使国家遭受严重危害和重大损失的。特指某些秘密文件资料，比如设计图纸、</span>
              </p>
              <p>
                <span>投标方案、电子帐本、程序源码、个人隐私以及一些包含重要信息的录像带和光盘等文件。</span>
              </p>
              <p>
                <span>2、机密：指标有“机密”密级的文件、简报等形式含有国家重要秘密、泄露会使国家的安全和利益</span>
              </p>
              <p>
                <span>遭受严重的损害的载体。有文件、简报、讲话材料，各种资料、报表、刊物，以文字、符号、图形、</span>
              </p>
              <p>
                <span>声、像等形式。</span>
              </p>
              <p>
                <span>3、秘密：可以称为私有文件，或者是因为某些原因，而不可以向大众公开的文件，如国家机密文件等。</span>
              </p>
              <p>
                <span>4、公开：没有什么影响，可以公开的。</span>
              </p>
            </template>
            <span class="promptIcon"><question-circle-outlined /></span>
          </a-tooltip>
        </template> -->
        <template v-else-if="column.key === 'isTemplate'"><span class="form-table-heard">是否文件模板</span></template>
        <template v-else-if="column.key === 'principalId'"><span class="form-table-heard">文件负责人</span></template>
        <!-- <template v-else-if="column.key === 'counterSignIds'"><span class="form-table-heard">文件会签人</span></template> -->
        <template v-else-if="column.key === 'keyword'"><span>关键字</span></template>
        <template v-else-if="column.key === 'mainContent'"><span>主要内容</span></template>
        <template v-else-if="column.key === 'applyReason'"><span>申请原因</span></template>
        <template v-else-if="column.key === 'operation'"><span class="form-table-heard">操作</span></template>
      </template>

      <!-- 嵌套子表格插槽 -->
      <template #expandedRowRender="{ record }">
        <a-table :columns="innerColumns" :data-source="record.versions" :row-key="(record) => record.id" :pagination="false">
          <template #bodyCell="{ column, record, text }">
            <template v-if="column.dataIndex === 'attachmentFile'">
              <span style="color: #02a7f0; cursor: pointer" @click="previewFile(record)">{{ text }}</span>
            </template>
            <template v-if="column.dataIndex === 'remark' && record.flag">
              <a-input style="margin: -5px 0" v-model:value="record.remark" @blur="inputValueRemark(record)" />
            </template>
            <template v-if="column.dataIndex === 'size'">
              <span>{{ changeByte(record.size) }}</span>
            </template>
            <template v-if="column.key === 'operation' && record.flag">
              <span v-if="data.length" @click="onDeleteDetail(record.id)" class="form-table-actions">删除</span>
            </template>
          </template>
        </a-table>
      </template>
    </a-table>
    <a-button type="dashed" @click="handleAdd" style="width: 100%">+ 添加</a-button>
  </div>
  <AssociatedUploadDiaLog
    v-model:visible="state.showUpload"
    v-if="state.showUpload"
    :data="state.showData"
    :showType="state.showType"
    :showIndex="state.showIndex"
    @fileData="getFileData"
  ></AssociatedUploadDiaLog>
</template>

<script setup lang="ts">
import type { TreeSelectProps, CascaderProps } from 'ant-design-vue';
import type { ShowSearchType } from 'ant-design-vue/es/cascader';
import { ExclamationCircleOutlined, DownOutlined, SearchOutlined } from '@ant-design/icons-vue';
import { onBeforeUnmount, onUpdated, ref, computed, createVNode, getCurrentInstance, reactive, watch, inject, nextTick } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { useRoute } from 'vue-router';
import { fileTree, findCanUseTree } from '@/config/api/publicFile';
import { fileByName, treeDataSubject, fileGet } from '@/config/api/documentApplication';
import { Api as ApiResource, getPreviewFileUrl } from '@/config/api/resourceFileInfo';
import { DYNAMICLAYERUPLOAD, DYNAMICLAYERCLEAR } from '@/mixins/subject/subject-types';
import { changeByte } from '@/utils/common';
import AssociatedUploadDiaLog from './associatedUploadDiaLog.vue';
import { fileGetPreviewFileUrl } from '@/config/api/personFile';

const route: any = useRoute();
const emit = defineEmits(['revisedData']);
const newArr = ref([]);
const state: any = reactive({
  showUpload: false,
  visible: false, // 文件关联上传
  showData: {}, // 当前数据行
  showType: 'REVISE',
  showIndex: null
});
// 初始化赋值
getViewData();
function getViewData() {
  if (['EDIT'].includes(route.query.showType)) {
    Promise.all([
      fileGet(route.query.id),
      findCanUseTree({}),
      treeDataSubject({
        parentId: 0
      })
    ]).then(([fileGetRes, fileTreeRes, treeDataSubjectRes]) => {
      const result = fileGetRes.data?.applyLists;
      result.map((item) => {
        item.isShowIcon = true;
        //非本次修订上传文件，不显示删除选项
        // item.versions.forEach((ver) => {
        //   if (ver.version !== 'V1.0') {
        //     ver.flag = true;
        //   }
        // });
      });
      data.value = result;
      console.log(data.value);
      getFileTree(fileTreeRes);
      getSubjectTree(treeDataSubjectRes);
      nextTick(() => {
        emit('revisedData', data.value);
      });
    });
  } else {
    Promise.all([
      findCanUseTree({}),
      treeDataSubject({
        parentId: 0
      })
    ]).then(([fileTreeRes, treeDataSubjectRes]) => {
      getFileTree(fileTreeRes);
      getSubjectTree(treeDataSubjectRes);
    });
  }
}

const fileNameData = ref([]);
const fileNameColumn = [
  { title: '文件名称', dataIndex: 'name', key: 'name', width: 30, align: 'center' },
  { title: '编码', dataIndex: 'code', key: 'code', width: 30, align: 'center' }
];
// 文件名称搜索
const searchValue = ref('');
const onSearch = async (value) => {
  console.log(value, 33);
  console.log(fileNameData.value, 55);
  const result = await fileByName({ name: '' });
  fileNameData.value = result.data;

  if (value !== '') {
    fileNameData.value = fileNameData.value.filter((item) => {
      return item.name.includes(value);
    });
  }
  console.log(fileNameData.value, 66);
};

async function launchName(index) {
  const params = { name: '' };
  const result = await fileByName(params);
  fileNameData.value = result.data;
  fileNameData.value.forEach((item) => {
    item.sum = index;
  });
}

function rowClick(record) {
  return {
    onClick: () => {
      record.version = `V${Number(record.version.slice(1, 2)) + 1}.0`;
      record.fileId = record.id;
      record.isShowIcon = true;
      Reflect.deleteProperty(record, 'id');
      data.value[record.sum] = record;
      defaultExpandedRowKeys.value = [record.code];
    }
  };
}

function filterData(arr) {
  arr?.forEach((item) => {
    newArr.value.push(item.countersignId);
  });
  return newArr.value;
}

const inputValueName = (record) => {
  record.nameRequired = false;
  if (record.name === undefined || record.name === '') {
    record.nameRequired = true;
    message.warning('此为必填项');
    return;
  }
};

// const filterOptionName = (valueName: string, fileNameData: any) => {
//   return fileNameData.name.toLowerCase().indexOf(valueName.toLowerCase()) >= 0;
// };

// 文件类型树状
const searchValueType = ref('');
const treeDataType = ref<TreeSelectProps['treeData']>([]);
function getFileTree(result) {
  if (result.success) {
    treeDataType.value = result.data;
  }
}

const inputValueType = (record) => {
  record.typeRequired = false;
  if (record.directoryId === '') {
    record.typeRequired = true;
    message.warning('此为必填项');
    return;
  }
};

// 保密等级下拉
// const LevelOptions: CascaderProps['options'] = [
//   {
//     label: '公开',
//     value: 4
//   },
//   {
//     label: '机密',
//     value: 2
//   },
//   {
//     label: '绝密',
//     value: 1
//   },
//   {
//     label: '秘密',
//     value: 3
//   }
// ];
// const inputValueSecurityLevel = (record) => {
//   record.securityLevelRequired = false;
//   if (!record.securityLevel) {
//     record.securityLevelRequired = true;
//     message.warning('此为必填项');
//     return;
//   }
// };

// 是否文件模板
const templateOptions: CascaderProps['options'] = [
  {
    label: '是',
    value: 1
  },
  {
    label: '否',
    value: 0
  }
];
const inputValueIsTemplate = (record) => {
  record.isTemplateRequired = false;
  if (record.isTemplate === null) {
    record.isTemplateRequired = true;
    message.warning('此为必填项');
    return;
  }
};

// 文件负责人和文件会签人下拉
const subjectOptions = ref<CascaderProps['options']>([]);
function getSubjectTree(result) {
  if (result.success) {
    subjectOptions.value = result.data;
  }
}

// 下拉框搜索
const filterOptionSubject = (input: string, subjectOptions: any) => {
  return subjectOptions.nickName.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const inputValuePerson = (record) => {
  record.personRequired = false;
  if (record.principalId === '') {
    record.personRequired = true;
    message.warning('此为必填项');
    return;
  }
};

// 备注
const inputValueRemark = (record) => {
  // data.value[record.index].remark = record.remark;
  console.log('一行数据', record);
  console.log('总数据', data.value);
};

// 表格展开
const defaultExpandedRowKeys = ref([]);
const rowData = (expanded, record) => {};

const columns = [
  { title: '序号', dataIndex: 'index', key: 'index', width: 80, defaultSortOrder: 'descend', customRender: ({ index }) => index + 1 },
  { title: '文件名称', dataIndex: 'name', key: 'name', width: 120 },
  { title: '文件编码', dataIndex: 'code', key: 'code', width: 120 },
  { title: '文件类型', dataIndex: 'directoryId', key: 'directoryId', width: 150 },
  { title: '版本号', dataIndex: 'version', key: 'version', width: 100 },
  // { title: '保密等级', dataIndex: 'securityLevel', key: 'securityLevel', width: 140 },
  { title: '是否文件模板', dataIndex: 'isTemplate', key: 'isTemplate', width: 150 },
  { title: '文件负责人', dataIndex: 'principalId', key: 'principalId', width: 200 },
  // { title: '文件会签人', dataIndex: 'counterSignIds', key: 'counterSignIds', width: 150 },
  { title: '关键字', dataIndex: 'keyword', key: 'keyword', width: 150 },
  { title: '主要内容', dataIndex: 'mainContent', key: 'mainContent', width: 150 },
  { title: '申请原因', dataIndex: 'applyReason', key: 'applyReason', width: 150 },
  { title: '操作', key: 'operation', width: 180, fixed: 'right' }
];

const data: any = ref([]);
const handleAdd = () => {
  data.value.push({
    name: '',
    directoryId: '',
    // securityLevel: '',
    isTemplate: null,
    principalId: '',
    // counterSignIds: [],
    keyword: '',
    mainContent: '',
    applyReason: '',
    versions: [],
    isShowIcon: false
  });
  defaultExpandedRowKeys.value = [];
};

// 主表删除项
const onDelete = (code) => {
  Modal.confirm({
    title: '是否确定删除',
    autoFocusButton: null,
    icon: createVNode(ExclamationCircleOutlined),
    okText: '确认',
    cancelText: '取消',
    onOk() {
      data.value = data.value.filter((item) => item.code !== code);
      emit('revisedData', data.value);
    }
  });
};

// 文件详情删除项
const onDeleteDetail = (id) => {
  Modal.confirm({
    title: '是否确定删除',
    autoFocusButton: null,
    icon: createVNode(ExclamationCircleOutlined),
    okText: '确认',
    cancelText: '取消',
    onOk() {
      data.value.forEach((item) => {
        if (item.versions.some((itemFile) => itemFile.id === id)) {
          item.newVersionId = null;
        }
        item.versions = item.versions.filter((itemFile) => itemFile.id !== id);
      });
      emit('revisedData', data.value);
    }
  });
};
const innerColumns = [
  { title: '序号', dataIndex: 'index', key: 'index', width: 70, defaultSortOrder: 'descend', customRender: ({ index }) => index + 1 },
  { title: '文件', dataIndex: 'attachmentFile', key: 'attachmentFile', width: 120 },
  { title: '备注', dataIndex: 'remark', key: 'remark', width: 120 },
  { title: '大小', dataIndex: 'size', key: 'size', width: 120 },
  { title: '上传时间', dataIndex: 'createdTime', key: 'createdTime', width: 150 },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: 120
  }
];

// 导入文件
const { proxy }: any = getCurrentInstance();
const onUpload = (record, index) => {
  proxy.$NotificationPubSub.pushParams({
    key: DYNAMICLAYERUPLOAD,
    value: {
      state: {
        size: '4096',
        beforeWithMethodRequireData: true,
        downloadRule: '支持扩展名：.rar .zip .doc .docx .pdf .jpg...',
        beforeWithMethod: (data) => {
          // 如果是多文件上传(data=[])此处还需更改
          record.newVersionId = data.id;
          // record.attachmentFile = data.name;
          // record.size = `${changeByte(data.size)}`;
          // record.createdTime = data.createdTime;
          record.versions = record.versions.filter((item) => item.hashSign !== data.hashSign);
          record.versions.push({
            attachmentFile: data.name,
            size: data.size,
            remark: '',
            createdTime: data.createdTime,
            flag: true,
            index: index,
            id: data.id,
            hashSign: data.hashSign
          });
          proxy.$NotificationPubSub.pushParams({ key: DYNAMICLAYERCLEAR });
        }
      }
    }
  });
};

// 文件关联上传
function associatedUpload(record, index) {
  state.showData = record;
  state.showIndex = index;
  state.showUpload = true;
}
const getFileData = (val) => {
  data.value.forEach((item, index) => {
    if (item.code === val.code) {
      data.value[index] = val;
    }
  });
};

// 预览文件
const previewFile = (record) => {
  const params = {
    id: record.id,
    expires: 2,
    timeUnit: 'HOURS'
  };
  if (record?.fileSource === 2) {
    fileGetPreviewFileUrl(params).then((result) => {
      if (result && result.success) {
        window.open(result.data);
      }
    });
  } else {
    getPreviewFileUrl(params).then((result) => {
      if (result && result.success) {
        window.open(result.data);
      }
    });
  }
};

nextTick(() => {
  emit('revisedData', data.value);
});

onBeforeUnmount(() => {
  proxy.$NotificationPubSub.clearParams();
});
</script>
<style lang="less" scoped>
.form-table-heard:before {
  content: '*';
  color: #ff4d4f;
}
.form-table-actions {
  color: #005aea;
  cursor: pointer;
  margin-right: 20px;
}
.promptIcon {
  cursor: pointer;
  color: #005aea;
}
.color {
  border-color: red;
}
.holder {
  color: red;
}
</style>
